import util from 'utils/util.js';
/**
 * 滚动到顶部
 * @that  当前
 * @scrollTop  滚动距离
 */
function goTopEvent(that, scrollTop) {
	let isPageScrollTo = false;
	if (uni.pageScrollTo) {
		isPageScrollTo = true;
	} else {
		isPageScrollTo = false;
	}
	if (scrollTop > 300 && !that.showGoTop) {
		that.setData({
			showGoTop: true,
			isPageScrollTo
		});
	} else if (scrollTop < 300 && that.showGoTop) {
		that.setData({
			showGoTop: false,
			isPageScrollTo
		});
	}
}
//判断是否固定到顶部
function scrollIsTabFixed(that, event) {
	if (that.tabOffsetTop !== null) {
		console.log(that.tabOffsetTop)
		const isTabFixed = that.isTabFixed,
			tmpIsTabFixed = event.scrollTop >= that.tabOffsetTop;
		if (isTabFixed != tmpIsTabFixed) that.setData({
			isTabFixed: tmpIsTabFixed,
		});
	}
}

//更新tab距离顶部距离
function updateTabOffsetTop(that) {
	if (uni.createSelectorQuery) {
		setTimeout(function() {
			const selectorQuery = uni.createSelectorQuery();
			selectorQuery.select('#tab').boundingClientRect();
			selectorQuery.selectViewport().scrollOffset();
			selectorQuery.exec((res) => {
				//console.log(res)
				if (!res[0] || !res[1]) return;
				if (res[1].scrollTop > 0) {
					if (res[0].top > 0) {
						that.tabOffsetTop = res[1].scrollTop + res[0].top;
					} else {
						that.tabOffsetTop = (res[1].scrollTop - Math.abs(res[0].bottom)) + res[0]
							.height * 2;
					}
				} else {
					that.tabOffsetTop = res[0].top;
				}
			});
		}, 1500)
	}
}
//属性判断
function attr(params, key) {
	// #ifdef MP-ALIPAY
	if (Object.prototype.hasOwnProperty.call(params, key)) {
		return true
	} else {
		return false
	}
	//#endif
	// #ifndef MP-ALIPAY
	if (params.hasOwnProperty(key)) {
		return true
	} else {
		return false
	}
	// #endif
}
/**
 * 没有时间限制的弹框
 * @title  提醒内容
 */

function showClickModal(msg, showCancel) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '提示',
			content: msg,
			showCancel,
			success(_res) {
				resolve(_res)
			}
		});
	})
}
/**
 * 显示有时间限制的弹框
 * @title  提醒内容
 */
function showTimeToast(title, time) {
	uni.showToast({
		title,
		duration: time ? time : 2000,
		icon: 'none',
		// #ifndef MP-TOUTIAO || MP-ALIPAY
		mask: true
		// #endif
	});
}

// 加载框
function showLoading(title) {
	getApp().globalData.showLoading = true;
	uni.showLoading({
		title: title,
		mask: true
	})
}

function hideLoading(title) {
	if (!getApp().globalData.showLoading) return;
	getApp().globalData.showLoading = false;
	uni.hideLoading({
		noConflict: true,
		success: (res) => {},
	})
}
/**
 * 保存数据事件
 * @key  本地缓存中指定的key
 * @data  需要存储的内容
 */
function setInfo(key, data) {
	try {
		uni.setStorageSync(key, data);
	} catch (event) {
		console.log(event);
	}
}
/**
 * 获取已保存数据
 * @key  本地缓存中置顶的key
 */
function getInfo(key) {
	try {
		let value = uni.getStorageSync(key);
		if (value) {
			return value;
		}
		return {};
	} catch (event) {
		console.log(event);
	}
	return null;
}

/**
 * 获取图片信息preimg
 */
function singleImgInfo(res) {
	return uni.pro.getImageInfo({
		src: res.preimg
	});
}

function getImgInfo(imgArr) {
	let pros = [];
	imgArr.forEach((row) => {
		pros.push(singleImgInfo(row));
	});
	return uni.pro.all(pros);
}

/**
 * 上传图片
 * @res  图片上传的api
 * @path  需要上传的图片
 */

function singleUpload(path, num) {
	if (num >= 100) {
		let ocr = num == 100 ? "face" : 'back'
		return uni.pro.uploadFile({
			url: uni.getStorageSync('serverurl') + 'api/v1/wap/files',
			filePath: path,
			name: 'image',
			header: {

			},
			formData: {
				ocr: ocr
			},
			// complete(res){
			//     console.log(res)
			// }
		});
	} else {
		return uni.pro.uploadFile({
			url: uni.getStorageSync('serverurl') + 'api/v1/wap/files',
			filePath: path,
			name: 'image',
			header: {

			},
			// complete(res){
			//     console.log(res)
			// }
		});
	}
}

/**
 * 上传图片
 * @scenario  应用名称
 * @num  上传的图片最大数量
 * func  Function
 */
function uploadImgs(num, func) {
	let count = num;
	if (num >= 100) {
		count = 1
	}
	let tempFile = '';
	uni.pro.chooseImage({
		count: count, //最多可以选择的图片张数，默认9
		sizeType: ['compressed'], // 指定是压缩图
		sourceType: ['album', 'camera'] // 可以指定来源是相册还是相机，默认二者都有
	}).then((res) => {
		tempFile = res.tempFilePaths;
		uni.showLoading({
			title: '上传中，请稍等...'
		});
		let pros = [];
		tempFile.forEach((path) => {
			pros.push(singleUpload(path, num));
		});

		return uni.pro.all(pros);
	}).then((_res) => {
		uni.hideLoading();
		func(_res, tempFile);
	});
}

/**
 * 查看大图
 * @imgUrl  图片路径
 * @imgList  图片列表
 */
function seeBigImg(imgUrl, imgList) {
	if (imgList.length === 0) {
		uni.previewImage({
			urls: [imgUrl] // 需要预览的图片http链接列表
		});
	} else {
		uni.previewImage({
			current: imgUrl, // 当前显示图片的http链接
			urls: imgList // 需要预览的图片http链接列表
		});
	}
}

function downVideo(url) {
	uni.downloadFile({
		url: url,
		success: function(res) {
			uni.saveVideoToPhotosAlbum({
				filePath: res.tempFilePath,
				success: function(file) {
					showTimeToast("下载成功")
				},
				fail: function(e) {
					console.info("uni.saveImageToPhotosAlbum error" + JSON.stringify(e));
					showTimeToast(JSON.stringify(e))
				}
			})
		},
		fail: function(e) {
			console.info("uni.downloadFile error" + JSON.stringify(e));
			showTimeToast(JSON.stringify(e))
		}
	})
}
/**
 * 下载多图
 */
function downMoreImg(imgs) {
	let idx = 0;
	Promise.all(imgs.map((url, index) => {
		console.log(url)
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success: function(res) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function(file) {
							resolve(file);
						},
						fail: function(e) {
							let msg = "uni.saveImageToPhotosAlbum error" +
								JSON.stringify(e)
							console.info(msg);
							showTimeToast('保存到相册失败')
							resolve(e);
						}
					})
				},
				fail: function(e) {
					console.info("uni.downloadFile error" + JSON.stringify(e));
					showTimeToast('下载失败')
					resolve(e);
				}
			}).onProgressUpdate((res) => {
				if (res.progress == 100) {
					idx += 1;
					if (Number(idx) === Number(imgs.length)) {
						uni.hideLoading();
						uni.showToast({
							title: '下载完成'
						});
					}
					console.log('下载进度：' + res.progress);
				}
			})
		});
	}))
}

/**
 * 打电话
 * @phone  手机号
 */
async function phoneCall(phone) {
	if (!phone) {
		await showClickModal('暂无联系电话！', false);
		return;
	}
	uni.makePhoneCall({
		phoneNumber: phone,
		success() {},
		fail() {}
	});
}
/**
 * 打开地图
 * @lat  经度
 * @lng  纬度
 */
function openMap(lat, lng) {
	uni.openLocation({
		latitude: Number(lat),
		longitude: Number(lng),
		// scale: Number(28)
	});
}
/**
 * 复制
 */
function copyTextToClipboard(text) {
	var textArea = document.createElement("textarea")

	textArea.style.position = 'fixed'
	textArea.style.top = 0
	textArea.style.left = 0
	textArea.style.width = '2em'
	textArea.style.height = '2em'
	textArea.style.padding = 0
	textArea.style.border = 'none'
	textArea.style.outline = 'none'
	textArea.style.boxShadow = 'none'
	textArea.style.background = 'transparent'
	textArea.value = text

	document.body.appendChild(textArea)

	textArea.select()

	try {
		var msg = document.execCommand('copy') ? '复制成功' : '复制失败'
		showTimeToast(msg);
	} catch (err) {
		alert('不能使用这种方法复制内容');
	}

	document.body.removeChild(textArea)
}

function copy(data) {
	// #ifdef MP
	uni.setClipboardData({
		data: data + "",
		success: function(res) {
			showTimeToast("复制成功")
		}
	})
	// #endif
	// #ifdef H5
	copyTextToClipboard(data)
	// #endif
}


/**
 * @param {*} param 
 * bindex 分包索引
 * bname 分包名称
 * pindex 页面索引
 * pname  页面名称
 * cindex 分包中的文件名称索引
 * cname 分包中的文件名称
 * url 跳转路径
 */

function goBackFunc(param) {
	let getPage = getCurrentPages();
	let isGoBack = false;
	let goBackIndex = 0;
	getPage.forEach((res, i) => {
		if (res && res.route) {
			let baoName = res.route.split("/")[param.bindex];
			//console.log(baoName == param.bname)
			let pageName = res.route.split("/")[param.pindex];
			//console.log(pageName +"--"+ param.pname)
			if (baoName == param.bname && pageName == param.pname) {
				if (attr(param, 'cindex')) {
					let currentName = res.route.split("/")[param.cindex];
					if (currentName == param.cname) {
						isGoBack = true;
						goBackIndex = getPage.length - (Number(i) + 1);
					}
				} else {
					isGoBack = true;
					goBackIndex = getPage.length - (Number(i) + 1);
				}
			}
		}
	})
	console.log(isGoBack)
	//console.log(param.url)
	if (isGoBack) {
		uni.navigateBack({
			delta: goBackIndex,
		})
	} else {
		uni.navigateTo({
			url: param.url,
		})
	}
}

function pageWebParam(path, name) {
	var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	if (reg.test(path))
		return unescape(RegExp.$2.replace(/\+/g, " "));
	return "";
}

function pageUrl(pname) {
	let getPage = getCurrentPages();
	let idx = -1;
	getPage.forEach((res, i) => {
		if (res && res.route) {
			let pageName = res.route.split("/")[2];
			if (pageName == pname) {
				idx = i;
			}
		}
	});
	let url = ""
	if (idx > -1) {
		let t = 'h5'
		if (getApp().globalData.isSocket) {
			t = "app"
		}
		url = uni.getStorageSync("serverurl") + t + "/#" + getPage[idx].__page__.fullPath;
	}
	return url;
}

// 判断是否为空对象
function isNullObj(data) {
	for (let key in data) {
		if (data.hasOwnProperty(key)) {
			return false;
		}
	}
	return true;
}
// 判断对象是否含有某个字段
function hasKey(data, key) {
	return data && data.hasOwnProperty(key);
}
//下载文件
function downFile(url) {
	uni.openDocument({
		filePath: uni.getStorageSync('serverurl') + url,
		showMenu: true,
		success: function(res) {
			console.log('打开文档成功');
		}
	});
}

function isIOS() {
	let isIphone = navigator.userAgent.includes('iPhone')
	let isIpad = navigator.userAgent.includes('iPad')
	return isIphone || isIpad
}

function getSdk(pname, callbck) {
	let url = "api/common/js_sdk"
	let val = {
		url: window.location.href
	}
	if (isIOS()) {
		let cc = null;
		sessionStorage.getItem('iosJssdkAi');
		if (cc == null || cc == 'undefined' || cc == undefined) {
			util.httpRequest(url, val, "POST").then(function(res) {
				if (res.results && attr(res.results, 'appid')) {
					res.results["appId"] = res.results.appid;
				}
				sessionStorage.setItem('iosJssdkAi', JSON.stringify(res.results))
				let data = res.results

				callbck(data)
			});
		} else {
			let data = JSON.parse(sessionStorage.getItem('iosJssdkAi'));
			callbck(data)
		}
	} else {
		util.httpRequest(url, val, "POST").then(function(res) {
			console.log(res)
			if (res.results && attr(res.results, 'appid')) {
				res.results["appId"] = res.results.appid;
			}
			let data = res.results
			callbck(data)
		});
	}
}

function filterHTMLTag(msg) {
	var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
	msg = msg.replace(/[|]*\n/, '') //去除行尾空格
	msg = msg.replace(/&npsp;/ig, ''); //去掉npsp
	msg = msg.replace(/\n/g, '')
	msg = msg.replace(/\r\n/g, '')
	msg = msg.replace('&nbsp', '')
	msg = msg.replace('&ldquo', '')
	return msg;
}

function jsApiCall(data, tourl, callback) {
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
			appId: data.appId,
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.package,
			signType: data.signType,
			paySign: data.paySign
		},
		function(res) {
			callback(res)
		}
	);
}
/**
 * 请求支付
 * @url  请求的api地址
 * @val  请求api的参数参数信息
 * @fun  返回Function
 */
function payment(data, tourl, callback) {
	if (typeof WeixinJSBridge === "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', jsApiCall(data, tourl, (res) => {
				callback(res)
			}), false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', jsApiCall(data, tourl, (res) => {
				callback(res)
			}));
			document.attachEvent('onWeixinJSBridgeReady', jsApiCall(data, tourl, (res) => {
				callback(res)
			}));
		}
	} else {
		jsApiCall(data, tourl, (res) => {
			callback(res)
		});
	}
}


/**
 * 下拉刷新
 * showLoad  是否线上加载框
 * len  导航长度
 * navIndexd  导航索引
 */
function refresh(that, showLoad = true, len = 0, navIndex = -1) {
	return new Promise((resolve, reject) => {
		if (that.isRefresh || that.isLoading) return;
		if (showLoad) {
			showLoading('刷新中...');
		}
		init(that, false, len, navIndex)

		that.isRefresh = true;
		resolve(true)
	})
}

/**
 * 上拉加载更多
 * navIndexd  导航索引
 */

function loadMore(that, navIndex = -1) {
	return new Promise((resolve, reject) => {
		let n = that.next;
		if (navIndex > -1) {
			n = that.next[navIndex]
		}
		if (that.loading || n == 0) return;
		that.loading = true
		that.isLoading = false;
		if (navIndex == -1) {
			that.page += 1;
		} else {
			that.page[navIndex] += 1;
		}

		resolve(true)
	})
}

/**
 * 初始化列表数据
 * clear  获取服务器数据之前，是否清空页面数据
 * len  导航长度
 * navIndexd  导航索引
 */
function init(that, clear = false, len = 0, navIndex = -1) {
	if (len == 0) {
		if (clear) {
			that.requestStatus = false
			that.list = []
		}
		that.next = 0
		that.page = 1;
	} else {
		if (navIndex == -1) {
			that.requestStatus = false
			that.list = []
			that.next = []
			that.page = []
			for (var i = 0; i < len; i++) {
				that.list[i] = []
				that.next[i] = 0
				that.page[i] = 1;
			}
		} else {
			that.page[navIndex] = 1;
		}
	}

	that.loading = false
	that.isLoading = true;
}
/** 
 * 获取列表数据
 * url api地址
 * val 参数
 * isPaging 是否分页
 * dimension  数组维数
 * navIndexd  导航索引
 */
async function getList(url, val, that, isPaging = true, dimension = 2, navIndex = -1) {

	let param = {}
	if (isPaging) {
		if (navIndex == -1) {
			param = {
				page: that.page,
				limit: that.limit,
			}
		} else {
			param = {
				page: that.page[navIndex],
				limit: that.limit,
			}
		}

	}
	if (that.keywords) {
		val["keywords"] = that.keywords
	}
	Object.assign(param, val)
	//console.log(param)
	let res = await util.httpRequest(url, param);
	if (res.code == 401) {
		return res;
	}
	if (that.isRefresh) {
		that.isRefresh = false;
		uni.stopPullDownRefresh();
	}
	if (that.isLoading) {
		that.isLoading = false;
		hideLoading()
	}
	if (isPaging) {
		res['size'] = that.page
	}
	//console.log(res)
	if (res.result === 'fail') {
		if (res.page == 1) {
			if (navIndex == -1) {
				that.list = []
			} else {
				that.list[navIndex] = []
			}
		}
		showTimeToast(res.msg);
		return res;
	}
	if (dimension == 2) {
		that.requestStatus = true;
		that.loading = false;
		if (navIndex == -1) {
			that.list[(that.page - 1)] = res.results
			that.next = res.next;
			if (that.page == 1) {
				that.list = [that.list[0]]
			}
		} else {
			that.list[navIndex][(that.page - 1)] = res.results
			that.next[navIndex] = res.next;
			if (that.page == 1) {
				let arr = []
				arr.push(res.results)
				that.list[navIndex] = arr
			}
		}
	} else if (dimension == 3) {
		let li = that.list;
		if (that.page == 1) {
			li = [
				[],
				[]
			];
		}

		if (res.results.length > 0) {
			res.results.forEach((rs, idx) => {
				if (idx % 2 == 0) {
					li[0].push(rs)
				} else {
					li[1].push(rs)
				}
			})
		}

		that.requestStatus = true
		that.list = li
		that.next = res.next
		that.loading = false
	} else if (dimension == 1) {
		let li = that.list;
		if (that.page == 1) {
			li = [];
		}

		if (res.results.length > 0) {
			li = li.concat(res.results)
		}
		that.requestStatus = true
		that.list = li
		that.next = res.next
		that.loading = false
	} else {
		that.requestStatus = true
		that.next = res.next
		that.loading = false
	}

	return res;
}

// 替换字符串指定位置
function changeStr(str, index, changeStr) {
	return str.substr(0, index) + changeStr + str.substr(index + changeStr.length);
}

async function userInfo() {
	if (getApp().globalData.userInfo) {
		let uInfo = getApp().globalData.userInfo
		uInfo['mobile'] = uInfo.phone ? changeStr(uInfo.phone, 3, '****') : '';
		return {
			result: "success",
			results: uInfo
		}
	}
	let url = "api/v1/wap/authorize"
	let res = await util.httpRequest(url);
	if (res.result == "success") {
		res.results['mobile'] = res.results.phone ? changeStr(res.results.phone, 3, '****') : '';
		getApp().globalData.userInfo = res.results
	}
	return res
}

function getParam(options) {
	console.log(options);
	setInfo("sence", "test")
	if (hasKey(options, "sence_key")) {
		setInfo("sence", options.sence_key)
	} else {
		let local = location.href;
		console.log(local);
		let sencekey = pageWebParam(local, "sence_key");
		console.log(sencekey);
		if (sencekey) {
			setInfo("sence", sencekey)
		}
	}
	if (hasKey(options, "code")) {
		setInfo("code", options.code)
	} else {
		let local = location.href;
		console.log(local);
		let code = pageWebParam(local, "code");
		console.log(code);
		if (code) {
			setInfo("code", code)
		}
	}
}

//获取节点数据
function selectorInfo(id, that) {
	return new Promise((resolve, reject) => {
		const query = uni.createSelectorQuery();
		query.select('#' + id).boundingClientRect()
		query.exec((rs) => {
			resolve(rs)
		});
	})
}

//获取顶部导航高度
function systeminfo() {
	const systeminfo = getApp().globalData.systeminfo || uni.getSystemInfoSync();

	return {
		windowWidth: systeminfo.windowWidth,
		windowHeight: systeminfo.windowHeight,
		platform: systeminfo.platform
	}
}

async function getBase(){
	let url = 'api/v1/wap/config'
	let res = await util.httpRequest(url);
	return res
}


function JsUBB(strContent) {
    //i替换
    let si = strContent.indexOf("[i]")
    if (si > -1) {
        strContent = strContent.replace('[i]', "<i>")
    }
    let ei = strContent.indexOf("[/i]")
    if (ei > -1) {
        strContent = strContent.replace('[/i]', "</i>")
    }
    //u替换
    let su = strContent.indexOf("[u]")
    if (su > -1) {
        strContent = strContent.replace('[u]', "<u>")
    }
    let eu = strContent.indexOf("[/u]")
    if (eu > -1) {
        strContent = strContent.replace('[/u]', "</u>")
    }
    //b替换
    let sb = strContent.indexOf("[b]")
    if (sb > -1) {
        strContent = strContent.replace('[b]', "<b>")
    }
    let eb = strContent.indexOf("[/b]")
    if (eb > -1) {
        strContent = strContent.replace('[/b]', "</b>")
    }

    return strContent;
}
/**
 * 富文本图片宽度自适应样式处理
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性： max-width: 100%;height:auto
 * 3.修改所有style里的width属性为max-width: 100%
 * 4.去掉<br />标签
 * @param {*} html 
 */
function formatRichText(html) {
    //正则匹配img标签，并且含有width,height
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        // 除去data-width 自定义属性
        match = match.replace(/data-width="[^"]+"/gi, '').replace(/data-width='[^']+'/gi, '');

        // style 样式设置及追加
        if (match.indexOf('style') < 0) { //不存在style属性 则设置自适应样式
            match = match.replace(/<\s*img/, '<img style="max-width:100%;height:auto;"')
        } else { // 存在style属性，则追加自适应样式
            match = match.replace(/style=("|')/, 'style=$1max-width:100%;height:auto;')
        }

        // 清除width和height属性
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });

    // 将所有标签style设置的width替换为max-width:100%
    // newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
    //     match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    //     return match;
    // });

    // 清除<br />换行
    // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    return JsUBB(newContent);
}

module.exports = {
	goTopEvent,
	scrollIsTabFixed,
	updateTabOffsetTop,
	showClickModal, //可点击的模态弹框
	showTimeToast, //不可点击的模态弹框
	showLoading, //加载框
	hideLoading, //隐藏加载框
	uploadImgs, //上传图片
	phoneCall, //拨打电话
	openMap, //查看地图
	seeBigImg, //查看大图
	downMoreImg, //下载多图
	getImgInfo, //获取图片信息
	downVideo, //下载视频
	setStorage: setInfo, //存缓存
	getStorage: getInfo, //获取缓存
	copy,
	isNullObj,
	goBackFunc,
	attr,
	hasKey,
	downFile,
	getList,
	init,
	loadMore,
	refresh,
	userInfo,
	payment,
	getSdk,
	pageWebParam,
	getParam,
	selectorInfo,
	systeminfo,
	getBase,
	formatRichText
};